package com.hfzy.ihk.web.freeswitchCall.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisFields;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisKey;
import ihk.house.callcenter.CloudCallHistoryManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: Administrator
 * @Date: 2019/1/23 10:48
 * @Description:
 */
@Component
public class PushDataToOracleBiz {


    @Autowired(required = false)
    CloudCallHistoryManager cloudCallHistoryManagerService;

    @Autowired
    RedisTemplate redisTemplate;

    Logger logger= LoggerFactory.getLogger(PushDataToOracleBiz.class);


    /**
     * 推送到Oracle的通话记录
     * @param callHistoryMap
     */
    public void pushData(Map<String,String> callHistoryMap){

        pushCallHistoryToOracle(callHistoryMap.get(RedisFields.CALL_HISTORY_SESSION_ID),callHistoryMap,false);
    };

    /**
     * 跑Job的时候推送到Oracle的通话记录
     * @param callHistoryMap
     */
    public void jobPushData(Map<String,String> callHistoryMap){

        pushCallHistoryToOracle(callHistoryMap.get(RedisFields.CALL_HISTORY_SESSION_ID),callHistoryMap,true);
    }


    /**
     *通话记录推送到Oracle
     * @param sessionId 对应的sessionId
     * @param callHistoryMap
     * @param isJob  如果是Job推送的话,推送成功需要删除
     */
    public void pushCallHistoryToOracle(String sessionId,Map<String,String> callHistoryMap,boolean isJob){

        logger.info("---------开始推送到呼叫记录到oracle,sessionId:"+sessionId);

        try {

            //以下主被叫互换,因为置业那边主叫为客户
//            String mainCallPhone=callHistoryMap.get("mainCallPhone");
//
//            String targetCallPhone=callHistoryMap.get("targetCallPhone");
//
//            callHistoryMap.put("mainCallPhone",targetCallPhone);
//
//            callHistoryMap.put("targetCallPhone",mainCallPhone);

            String jsonData = JSONObject.toJSONString(callHistoryMap);


            long startTime = System.currentTimeMillis();

            String rs = cloudCallHistoryManagerService.saveOrUpdate(jsonData);
            logger.info("--------------push oracle rs{},data:{}",rs,jsonData);
            if (!StringUtil.isEmpty(rs)&&"1".equals(JSON.parseObject(rs).get("code"))){

                if (isJob){
                    //推送成功,删除redis的key,防止堆积
                    removeRedis("record",sessionId);
                }

                logger.info("---->推送到呼叫记录到oracle成功,耗时"+(System.currentTimeMillis()-startTime)+"毫秒,sessionId:"+sessionId);

            }else {

                logger.info("---->推送到呼叫记录到oracle失败,将存入redis,sessionId:"+sessionId);

                setReids("record",sessionId);
            }
        } catch (Exception e) { //发生异常,不要删除key
            logger.error("推送置业Oracle错误>> sessionId:{}",sessionId,e);
            setReids("record",sessionId);
        }


    };

    /**
     * 将需要推送录音到Oracle的呼叫记录的sessionId保存起来
     * @param
     * @param sessionId
     */
    public void setSessionIdToReids(String sessionId){
        try {

            redisTemplate.opsForSet().add(RedisKey.PUSH_URL_TO_ORACLE_SET, sessionId);

            logger.info(">>>>>>>>将需要推送录音url到Oracle的sessionId保存到redis成功！,sessionId:"+sessionId);

        }catch ( Exception e){
            logger.error(">>>>>>>>将需要推送录音url到Oracle的sessionId保存到redis失败！,sessionId:"+sessionId,e);
        }
    }



    /**
     * 将推送失败数据存入redis
     * @param type
     * @param sessionId
     */
    public void setReids(String type,String sessionId){
        try {
            if ("record".equals(type)) {
                redisTemplate.opsForSet().add(RedisKey.PUSH_RECORD_TO_ORACLE_FAILED_SET, sessionId);
            } else if ("url".equals(type)) {
                redisTemplate.opsForSet().add(RedisKey.PUSH_URL_TO_ORACLE_FAILED_SET, sessionId);
            }
            logger.info(">>>>>>>>将推送Oracle失败数据保存到redis成功！,sessionId:"+sessionId);
        }catch ( Exception e){
            logger.error(">>>>>>>>将推送Oracle失败数据保存到redis失败！,essionId:"+sessionId,e);
        }
    }


    /**
     *将推送录音url成功的sessionId删除
     * @param sessinId
     */
    public void removeUrlRedis(String sessinId){

        try{

            redisTemplate.opsForSet().remove(RedisKey.PUSH_URL_TO_ORACLE_SET,sessinId);

            logger.info("删除推送录音url的sessionId成功,sessionId:"+sessinId);

        }catch (Exception e){

            logger.error("删除推送录音url的sessionId失败,sessionId:"+sessinId);
        }

    }

    /**
     * 将推送失败数据存入redis的sessionId删除
     * @param type
     * @param sessionId
     */
    public void removeRedis(String type,String sessionId){
        try {
            if ("record".equals(type)) {
                redisTemplate.opsForSet().remove(RedisKey.PUSH_RECORD_TO_ORACLE_FAILED_SET, sessionId);
            } else if ("url".equals(type)) {
                redisTemplate.opsForSet().remove(RedisKey.PUSH_URL_TO_ORACLE_FAILED_SET, sessionId);
            }
            logger.info(">>>>>>>>将推送Oracle失败数据的redisKey删除成功！sessionId:"+sessionId);
        }catch ( Exception e){
            logger.error(">>>>>>>>将推送Oracle失败数据的redisKey删除失败！sessionId:"+sessionId,e);
        }
    }

    /**
     * 录音url推送到Oracle
     * @param sessionId
     * @param record_file
     */
    public void pushRecordUrlToOracle(String sessionId, String record_file) {

        Map<String,String> jsonMap=new HashMap<>();

        jsonMap.put(RedisFields.CALL_HISTORY_SESSION_ID,sessionId);

        jsonMap.put(RedisFields.CALL_HISTORY_RECORD_FILE_URL,record_file);

        long startTime = System.currentTimeMillis();

        try {

            logger.info("------>>开始推送录音到Oracle,sessionId:"+sessionId);

            String rs = cloudCallHistoryManagerService.updateCloudCallHistoryBySessionId(JSON.toJSONString(jsonMap));


            if (!StringUtil.isEmpty(rs)&&"1".equals(JSON.parseObject(rs).get("code"))){

                logger.info("---->推送到录音url到oracle成功,耗时"+((startTime-System.currentTimeMillis())/1000)+"秒,sessionId:"+sessionId);

                //删除redis的key
                removeUrlRedis(sessionId);

            }else {

                logger.info("---->推送到录音到oracle失败,不删除redis的key,sessionId:"+sessionId);

            }
        } catch (Exception e) {
            logger.error("推送录音url到置业Oracle错误,不删除redis的key sessionId:{}",sessionId,e);

        }

    }


}
